<template>
	<coreshop-page :title="state.pageTitle" mode="left">
		<view class="layout-address-box">

			<view class="address-box">
				<view class="item">
					<view class="lab">姓名</view>
					<view class="val">
						<uv-input placeholder="请输入姓名" border="surround" v-model="state.form.name"></uv-input>
					</view>
				</view>
				<view class="item">
					<view class="lab">手机号</view>
					<view class="val">
						<uv-input placeholder="请输入手机号" type="number" border="surround"
							v-model="state.form.mobile"></uv-input>
					</view>
				</view>
				<view class="item">
					<view class="lab">省市县</view>
					<view class="val" @click="handleShowCityPicker">
						<uv-input placeholder="请选择省市县" border="surround" v-model="state.city" :readonly="true"
							suffixIcon="arrow-down" suffixIconStyle="color: #909399"></uv-input>
					</view>
				</view>
				<view class="item">
					<view class="lab">街道社区</view>
					<view class="val" @click="handleGoToMap">
						<uv-input v-if="shopConfigStore.config?.allowAddressToUseMap == ShowAllowAddressToUseMap.yes"
							placeholder="请选择街道社区" border="surround" v-model="state.form.street" :readonly="true"
							suffixIcon="map-fill" suffixIconStyle="color: #5ac725"></uv-input>
						<uv-input v-else placeholder="请选择街道社区" border="surround" v-model="state.form.street"></uv-input>
					</view>
				</view>
				<view class="item">
					<view class="lab">详细地址</view>
					<view class="val">
						<uv-textarea v-model="state.form.address" placeholder="请输入详细地址"></uv-textarea>
					</view>
				</view>
				<view class="item isDefault">
					<view class="lab">是否设为默认</view>
					<view class="val">
						<uv-switch v-model="state.isDefault" activeColor="#D33123" size="20"></uv-switch>
					</view>
				</view>
			</view>

			<coreshop-fixed-bottom-button :radius="100" title="保存" :loading="loading"
				@onClick="handleSaveShip"></coreshop-fixed-bottom-button>

			<coreshop-select-city :show="state.showSelectCity" :pickerValue="state.pickerValue"
				@handleClosePicker="handleClosePicker"
				@handleConfirmPicker="handleConfirmPicker"></coreshop-select-city>
		</view>
	</coreshop-page>
</template>
<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
	import { AddressPageTitltEnum, ShowAllowAddressToUseMap } from '@/core/enum';
	import { queryAreaId, querySaveUserShip, queryShipDetail } from '@/core/api';
	import type { Response, ShopConfigStoreType, AddressType } from '@/core/models';
	import { useShopConfigStore } from '@/core/store';
	import { handleShowToast } from '@/core/utils';
	import { useLoadingFn } from '@/core/hooks';
	import { mobile } from '@/uni_modules/uv-ui-tools/libs/function/test.js';
	
	interface QueryParams {
		type : string;
		id : string | number;
	}
	// #ifdef MP-WEIXIN
	const chooseLocation = requirePlugin('chooseLocation');
	// #endif

	// 获取项目配置
	const shopConfigStore : ShopConfigStoreType = useShopConfigStore();

	const state = reactive<{
		pageTitle : string;
		isDefault : boolean;
		showSelectCity : boolean;
		city : string;
		longitude : number;
		latitude : number;
		region : Array<string>;
		shipId : number | string;
		submitStatus : boolean;
		pickerValue : string;
		form : {
			name : string;
			mobile : string;
			address : string;
			areaId : number;
			longitude : number | string;
			latitude : number | string;
			street : string;
			id ?: string | number;
		};
	}>({
		pageTitle: '',
		isDefault: false,
		showSelectCity: false,
		city: "",
		longitude: 0,
		latitude: 0,
		region: [],
		shipId: 0,
		submitStatus: true,
		pickerValue: '',
		form: {
			name: "",
			mobile: "",
			address: "",
			areaId: 0,
			longitude: 0,
			latitude: 0,
			street: "",
		}
	});


	const loading = ref(false);
	const handleSaveShip = useLoadingFn(onSaveShip, loading)


	onShow(() => {
		// #ifdef MP-WEIXIN
		const chooseLocation = requirePlugin('chooseLocation');
		const location = chooseLocation.getLocation();
		// #endif

		// #ifdef APP-PLUS || APP-PLUS-NVUE
		const location = uni.getLocation();
		// #endif

		if (location) {
			state.form.latitude = location.latitude;
			state.form.longitude = location.longitude;
			state.region = [location.province, location.district, location.city];
			state.form.street = location.name;
			state.form.address = location.address;
		}
	});

	onLoad((query : QueryParams) => {
		state.pageTitle = query?.type === AddressPageTitltEnum.add ? '新增地址' : '编辑地址';
		if (query.id) {
			state.shipId = query.id;
			getShipInfo();
		}
		/** 开启定位 */
		if (shopConfigStore.config?.allowAddressToUseMap == ShowAllowAddressToUseMap.yes) {
			getMyLocation();
		}
	});

	onUnload(() => {
		// 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
		// #ifdef MP-WEIXIN
		chooseLocation.setLocation(null);
		// #endif
	});

	/** 获取用户地理位置 */
	const getMyLocation = () => {
		// #ifdef MP-WEIXIN
		wx.getFuzzyLocation({
			type: 'wgs84',
			success(res : any) {
				state.latitude = res.latitude
				state.longitude = res.longitude
			},
			fail(e : any) {
				handleShowToast('获取您的经纬度坐标失败');
			}
		})
		// #endif

		// #ifndef MP-WEIXIN
		uni.getLocation({
			type: 'wgs84',
			success(res : any) {
				state.longitude = res.longitude;
				state.latitude = res.latitude;
			},
			fail() {
				handleShowToast('获取您的经纬度坐标失败');
			}
		});
		// #endif
	}

	/** 获取地址信息 */
	const getShipInfo = async () => {
		const shipDetail : Response<AddressType> = await queryShipDetail({ id: state.shipId });
		if (shipDetail.status) {
			state.form.name = shipDetail.data.name;
			state.form.mobile = shipDetail.data.mobile;
			state.form.longitude = shipDetail.data.longitude;
			state.form.latitude = shipDetail.data.latitude;
			state.form.areaId = shipDetail.data.areaId;
			state.form.street = shipDetail.data.street;
			state.form.address = shipDetail.data.address;
			state.isDefault = shipDetail.data.isDefault;
			state.city = shipDetail.data.areaName;
			state.pickerValue = shipDetail.data.areaName;
		} else {
			handleShowToast('获取收货地址信息出现问题');
		}
	}

	/** 显示省市区选择弹框 */
	const handleShowCityPicker = () => {
		state.showSelectCity = true;
	}

	/** 关闭省市区选择弹框 */
	const handleClosePicker = () => {
		state.showSelectCity = false;
	}

	/** 省市区确认选择 */
	const handleConfirmPicker = async (data : any) => {
		const areaId : Response<number> = await queryAreaId({
			provinceName: data[0].label,
			provinceId: data[0].value,
			cityName: data[1].label,
			cityId: data[1].value,
			countyName: data[2].label,
			countyId: data[2].value,
		})
		if (areaId.status) {
			state.form.areaId = areaId.data;
			state.city = `${data[0].label} ${data[1].label} ${data[2].label}`;
		} else {
			uni.showModal({
				title: '提示',
				content: '地区选择出现问题，请重新选择地区',
				showCancel: false
			});
		}
	}

	/** 去定位 */
	const handleGoToMap = () => {
		if (shopConfigStore.config?.allowAddressToUseMap != ShowAllowAddressToUseMap.yes) {
			return;
		}
		// #ifdef MP-WEIXIN
		const txMapkey = shopConfigStore?.config?.qqMapKey; //使用在腾讯位置服务申请的key
		const referer = shopConfigStore?.config?.shopName; //调用插件的app的名称
		const location = JSON.stringify({
			latitude: state.form.latitude == "" ? state.latitude : state.form.latitude,
			longitude: state.form.longitude == "" ? state.longitude : state.form.longitude
		});
		wx.navigateTo({
			url: `plugin://chooseLocation/index?key=${txMapkey}&referer=${referer}&location=${location}&category=${''}`
		});
		// #endif

		// #ifdef MP-ALIPAY
		my.chooseLocation({
			latitude: state.form.latitude == "" ? state.latitude : state.form.latitude,
			longitude: state.form.longitude == "" ? state.longitude : state.form.longitude,
			success: function (res : any) {
				state.form.latitude = res.latitude;
				state.form.longitude = res.longitude;
				state.form.street = res.address;
			},
			fail: function () { }
		});
		// #endif

		// #ifdef APP-PLUS || APP-PLUS-NVUE
		uni.chooseLocation({
			success: (res : any) => {
				state.form.street = res.name;
				state.form.latitude = res.latitude;
				state.form.longitude = res.longitude;
			}
		});
		// #endif
	}

	/** 提交地址 */
	async function onSaveShip() {
		if (!state.submitStatus) {
			return;
		}
		if (!state.form.name) {
			handleShowToast('请输入收货人姓名'); return;
		}
		if (!state.form.mobile) {
			handleShowToast('请输入收货人手机号'); return;
		}
		if (!mobile(state.form.mobile)) {
			handleShowToast('收货人手机号格式不正确'); return;
		}
		if (state.form.areaId <= 0) {
			handleShowToast('请选择地区信息'); return;
		}
		if (!state.form.street) {
			handleShowToast('请选择街道'); return;
		}
		if (shopConfigStore.config?.allowAddressToUseMap == ShowAllowAddressToUseMap.yes && (!state.form.latitude || !state.form.longitude)) {
			handleShowToast('请选择街道获取经纬度'); return;
		}

		let data = {
			name: state.form.name,
			address: state.form.address,
			mobile: state.form.mobile,
			isDefault: state.isDefault ? 1 : 2,
			areaId: state.form.areaId,
			longitude: state.form.longitude,
			latitude: state.form.latitude,
			street: state.form.street,
		}
		if (state.shipId) {
			data['id'] = state.shipId
		}
		const userShip = await querySaveUserShip(data);
		if (userShip.status) {
			state.submitStatus = false;
			handleShowToast(userShip.msg, 'success', () => {
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					});
				}, 2000)
			})
		} else {
			handleShowToast(userShip.msg);
		}
	}
</script>
<style lang="scss" scoped>
	@import './index.scss';
</style>